package com.wanlian.encrypt;

import com.wanlian.util.Base64Utils;
import com.wanlian.util.Utils;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;


/**
 * 对文件加签、验签工具类
 * 生成私钥：openssl genrsa -out rsa_private_key.pem 1024
 * 私钥还不能直接被使用，需要进行PKCS#8编码：openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
 * 根据私钥生成公钥：openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
 * 使用私钥sha512签名：openssl dgst -sha512 -sign rsa_private_key.pem -out xx.tar.gz.sign xx.tar.gz
 * 使用公钥sha512验签：openssl dgst -verify rsa_public_key.pem -sha512 -signature xx.tar.gz.sign xx.tar.gz
 */
public class RsaEncrypt {
    /**
     * 私钥
     */
    private RSAPrivateKey privateKey;

    /**
     * 公钥
     */
    private RSAPublicKey publicKey;

    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获取私钥
     *
     * @return 当前的私钥对象
     */
    public RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * 获取公钥
     *
     * @return 当前的公钥对象
     */
    public RSAPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * 随机生成密钥对
     */
    public void genKeyPair() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        byte[] seed=HexUtil.decode("f954b4fa5ee6c108589ea220be837776e977cf934a9dabfb970650915d0b6d07");

        keyPairGen.initialize(512, new SecureRandom(seed));
        KeyPair keyPair = keyPairGen.generateKeyPair();
        this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey = (RSAPublicKey) keyPair.getPublic();

        String privatecode = HexUtil.encode(this.privateKey.getEncoded());
        String publiccode = HexUtil.encode(this.publicKey.getEncoded());
        System.out.println(privatecode);
        System.out.println(publiccode);


//        RIPEMD160Digest digest = new RIPEMD160Digest();
//        digest.update(this.privateKey.getEncoded(), 0, this.privateKey.getEncoded().length);
//        byte[] ripemd160Bytes = new byte[digest.getDigestSize()];
//        digest.doFinal(ripemd160Bytes, 0);

        System.out.println("ripemd160加密=" + HexUtil.encode(seed));


    }


    /**
     * 随机生成密钥对
     */
    public void genKeyPair(String code) {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] seed=HexUtil.decode(code);
        keyPairGen.initialize(512, new SecureRandom(seed));
        KeyPair keyPair = keyPairGen.generateKeyPair();

        this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey = (RSAPublicKey) keyPair.getPublic();

        //String privatecode = HexUtil.encode(this.privateKey.getEncoded());
        //String publiccode = HexUtil.encode(this.publicKey.getEncoded());



        RIPEMD160Digest digest = new RIPEMD160Digest();
        digest.update(this.privateKey.getEncoded(), 0, this.privateKey.getEncoded().length);
        byte[] ripemd160Bytes = new byte[digest.getDigestSize()];
        digest.doFinal(ripemd160Bytes, 0);

        //System.out.println(HexUtil.decode(privatecode));
        System.out.println("地址："+HexUtil.encode(ripemd160Bytes));
        System.out.println("私钥："+code);



//        byte[] checksum = new byte[4];
//        System.arraycopy(twiceSha256Bytes, 0, checksum, 0, 4);
//        System.out.println("checksum=" + HexUtil.encode(checksum));




    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public void loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            this.publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 加载私钥
     *
     * @param privateKeyStr 私钥文件名
     * @return 是否成功
     * @throws Exception
     */
    public void loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            this.privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 加密过程
     *
     * @param publicKey     公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 解密过程
     *
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * Main 测试方法
     *
     * @param args
     */

    //public String get

    public static void main(String[] args) {
        RsaEncrypt rsaEncrypt = new RsaEncrypt();
        rsaEncrypt.genKeyPair(Utils.getUUID());

        // 测试字符串
        String aescode = Utils.getGuid();

        String content = "111111111111111111111111222222222222222222222222111111111111111111111112222222222";
        try {

            // 先通过rsa加密
            byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), aescode.getBytes());

            //String xxcode = AESEncrypt.AESEncode(aescode, content);


            // 解密
            byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(),
                    cipher);
            //System.out.println("rsa 加密："+new String(plainText));

            String xxcode = AESEncrypt.AESEncode(aescode, content);

            //System.out.println("aes加密后："+xxcode);
            System.out.println("aes解密后："+AESEncrypt.AESDncode(aescode, xxcode));

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}